package com.emcom.gotour.mvc.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.emcom.gotour.enums.PagingAction;
import com.emcom.gotour.mvc.model.TourContentModel;
import com.emcom.gotour.service.TourCategoryService;
import com.emcom.gotour.service.TourManageService;
import com.emcom.gotour.utils.Paging;
import com.emcom.gotour.utils.PagingUtils;
import com.emcom.gotour.vo.TourContentVO;

@Controller
public class TourPagingController {

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private TourManageService tourManageService;

	@Autowired
	private TourCategoryService tourCategoryService;

	@RequestMapping(value={"/admin/tour_paging.html","/admin/tour.html"})
	public String paging(HttpServletRequest request) {
		String subject = request.getParameter("subject");
		String typeId = request.getParameter("typeId");
		String category = request.getParameter("category");
		String page = request.getParameter("page");
		String action = request.getParameter("action");
		if(StringUtils.isNotEmpty(subject) || StringUtils.isNotEmpty(typeId) || StringUtils.isNotEmpty(category)) {
			Paging paging = PagingUtils.loadPaging(request, TourContentModel.PAGING_NAME);
			if(paging == null) {
				PagingUtils.forceInitPaging(request, tourManageService.queryMultiContent(subject, typeId, category), PagingUtils.PAGE_SIZE, TourContentModel.PAGING_NAME);
				paging = PagingUtils.loadPaging(request, TourContentModel.PAGING_NAME);
			}
			PagingUtils.forceInitPaging(request, tourManageService.queryMultiContent(subject, typeId, category), paging.getPageSize(), TourContentModel.PAGING_NAME);
		}
		if(StringUtils.isEmpty(page)) {
			page = String.valueOf(1);
		}
		if(StringUtils.isEmpty(action)) {
			action = PagingAction.FIRST.name();
		}
		Paging paging = PagingUtils.loadPaging(request, TourContentModel.PAGING_NAME);
		if(paging == null) {
			PagingUtils.forceInitPaging(request, tourManageService.queryMultiContent(subject, typeId, category), PagingUtils.PAGE_SIZE, TourContentModel.PAGING_NAME);
			paging = PagingUtils.loadPaging(request, TourContentModel.PAGING_NAME);
		}
		paging = PagingUtils.paging(PagingAction.valueOf(action), paging, Integer.valueOf(page));
		PagingUtils.savePaging(request, paging, TourContentModel.PAGING_NAME);
		List<TourContentVO> tourContentVOList = TourContentModel.buildTourContentVOList(paging.getPagingList());
		TourContentModel.getView(request, messageSource, tourCategoryService, tourContentVOList);
		return "/admin/tour";
	}

}
